package com.example.board.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.example.board.common.R;
import com.example.board.pojo.vo.ExcelListVo;
import com.example.board.service.SalesPlanService;
import com.example.board.util.ExcelMergeUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
@Api(tags = "销售计划汇报",value = "销售计划汇报")
@RequiredArgsConstructor
public class SalesPlanController {

    private  final SalesPlanService salesPlanService;

    @ApiOperation("总览数据")
    @PostMapping(value = "/sale-plan-board/total-static")
    public R getSalesmanRepurchase(String province, String  region, String type, String startTime) {
        return R.ok(salesPlanService.getSalesmanRepurchase(province,region,type,startTime));
    }

    @ApiOperation("筛选业务员")
    @PostMapping(value = "/sale-plan-board/salesman-static")
    public R getSalesmanStatic(String id,String startTime) {
        return R.ok(salesPlanService.getSalesmanStatic(id,startTime));
    }


    @GetMapping("/salesman-board/salesman-excels")
    @ApiOperation(value = "下载excels")
    public R getSalesmanExcel(HttpServletResponse response,
                              HttpServletRequest request,
                              String province,
                              String  region,
                              String deptName,
                              String startTime) throws IOException {

        try {
            //获取数据 http://localhost:8800/api/salesman-board/salesman-excels
//            List<List<ExcelListVo>> data = salesPlanService.getAll(province, region, deptName, startTime);
        List<ExcelListVo> data = salesPlanService.getAll(province,region,deptName,startTime);
//            List<Map<String, Object>> data = salesPlanService.getAll(province, region, deptName, startTime);
//            if (CollectionUtils.isEmpty(data)) {
//                data.add(new ExcelListVo());
//            }
            //需要合并的列
            int[] mergeColumeIndex = {0};
            // 从第二行后开始合并
            int mergeRowIndex = 3;
            if (StringUtils.isEmpty(startTime)) {
                startTime = ((DateTime.now() + "").split(" ")[0].split("-")[0]) +"-"+ ((DateTime.now() + "").split(" ")[0].split("-")[1]);
            }

            List<List<String>> headList = Lists.newArrayList();
            headList.add(Lists.newArrayList("服务商"));
            headList.add(Lists.newArrayList("业务员"));
//            headList.add(Lists.newArrayList("目标"));
            List<String> tartList = Lists.newArrayList("录入拜访","定制成交","标品袋");
            List<String> integerList = Lists.newArrayList(startTime);
            integerList.forEach(
                    moth->{
                        tartList.forEach(
                                t->{
                                    headList.add(Lists.newArrayList("总目标",moth+"月",t));
                                }
                        );
                    }
            );

            //attachment指定独立文件下载  不指定则回浏览器中直接打开
            String fileName = "业务订单导出_" + DateUtil.formatDate(new Date()) + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //导出excel
             EasyExcel.write(response.getOutputStream(), ExcelListVo.class)
                     .head(headList)
                    .registerWriteHandler(new ExcelMergeUtil(mergeRowIndex,mergeColumeIndex))
                    .sheet("业务订单").doWrite(data);

            log.info("业务订单导出end");
        } catch (Exception e) {
            log.error("业务订单导出异常打印:", e);
        } finally {

            try {
                response.flushBuffer();
                response.getOutputStream().flush();
                response.getOutputStream().close();
            } catch (IOException e) {
                log.error("业务订单导出输出流关闭失败: {}", e);
            }
        }


//        //1，找出模板文件，并转化为输入流：templateFileInputStream；
//        org.springframework.core.io.Resource resource = new ClassPathResource("业务订单导出.xlsx");
//        InputStream templateFileInputStream = resource.getInputStream();
//        //2，outputStream：要导出的文件的输出流；
//        OutputStream outputStream = response.getOutputStream();
//        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templa
//        teFileInputStream).build();
//        try {
//            WriteSheet writeSheet = EasyExcel.writerSheet("业务订单").build();
//            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
//            //3，往sheet表中填充数据：
//            excelWriter.fill(data, fillConfig, writeSheet);
//            //4，设置输出流格式以及文件名：
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/json;charset=utf-8");
//            String fileName = URLEncoder.encode("业务订单导出", "UTF-8").replaceAll("\\+", "%20");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//        } finally {
//            //5，最后，千万别忘记finish，关闭IO流；
//            if (excelWriter != null) {
//                excelWriter.finish();
//            }
//        }


        return R.ok();
    }



}
